package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.CollectionBehaviorMapper;
import com.heima.article.service.CollectionBehaviorService;
import com.heima.common.redis.CacheService;
import com.heima.feign.article.IArticleClient;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollectionBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.BehaviorEnums;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 许敦军
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/1/25 19:30:10
 */
@Service
@Slf4j
public class CollectionBehaviorServiceImpl implements CollectionBehaviorService {

    @Autowired
    private CacheService cacheService;
    @Autowired
    private IArticleClient iArticleClient;

    /**
     * 收藏行为
     *
     * @param collectionBehaviorDto 收集行为dtoc
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto collectionBehaviorDto) {
        // 数据校验
        if (collectionBehaviorDto == null || collectionBehaviorDto.getEntryId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 判断是否登陆
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 先判断数据库中是否有该数据
        String collectionData = (String) cacheService.hGet(BehaviorEnums.COLLECTION_BEHAVIOR + user.getId(), collectionBehaviorDto.getEntryId().toString());
        if(StringUtils.isNotEmpty(collectionData) && collectionBehaviorDto.getOperation() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //如果是空的，则添加
        if(collectionBehaviorDto.getOperation() == 0){
            log.info("收藏文章");
            //收藏，则添加
            cacheService.hPut(BehaviorEnums.COLLECTION_BEHAVIOR+user.getId(), collectionBehaviorDto.getEntryId().toString(), JSON.toJSONString(collectionBehaviorDto));
            //添加数据到数据库当中
            iArticleClient.addCollection(collectionBehaviorDto);

        }else{
            log.info("取消收藏");
            //取消收藏，删除redis中的数据
            cacheService.hDelete(BehaviorEnums.COLLECTION_BEHAVIOR+user.getId(), collectionBehaviorDto.getEntryId().toString());
            iArticleClient.addCollection(collectionBehaviorDto);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
